import json
import os
import time
import tkinter as tk
from tkinter import simpledialog, messagebox
from openai import OpenAI
from wxauto import WeChat


CONFIG_FILE = "config.json"


class WeChatBot:
    def __init__(self):
        self.config = self.__load_or_create_config()

        # 初始化 OpenAI 客户端
        self.client = OpenAI(
            api_key=self.config["api_key"],
            base_url=self.config["base_url"]
        )

        # 初始化微信控制器
        self.friend_name = self.__get_friend_name()
        if not self.friend_name:
            messagebox.showerror("错误", "未输入微信昵称，程序退出。")
            exit()

        self.prompt = self.__get_prompt()
        if not self.prompt:
            messagebox.showerror("错误", "未输入提示词，程序退出。")
            exit()

        self.wx = WeChat()
        self.wx.AddListenChat(who=self.friend_name)
        messagebox.showinfo("启动成功", f"正在监听：{self.friend_name}，请保持微信在前台运行")

        self.last_messages = {}

    def __load_or_create_config(self):
        if os.path.exists(CONFIG_FILE):
            with open(CONFIG_FILE, "r", encoding="utf-8") as f:
                return json.load(f)
        else:
            return self.__create_config()

    def __create_config(self):
        root = tk.Tk()
        root.withdraw()
        api_key = simpledialog.askstring("首次运行配置", "请输入你的 OpenAI / DeepSeek API Key：")
        base_url = simpledialog.askstring("API 地址", "请输入 API 接口地址：", initialvalue="https://api.deepseek.com/v1")

        if not api_key or not base_url:
            messagebox.showerror("错误", "API Key 或地址不能为空，程序退出。")
            exit()

        config = {"api_key": api_key, "base_url": base_url}
        with open(CONFIG_FILE, "w", encoding="utf-8") as f:
            json.dump(config, f, indent=4)
        return config

    def __get_friend_name(self):
        root = tk.Tk()
        root.withdraw()
        return simpledialog.askstring("监听设置", "请输入你要监听的微信好友昵称：")

    def __get_prompt(self):
        root = tk.Tk()
        root.withdraw()
        use_default = messagebox.askyesno("提示词选择", "是否使用默认提示词？")
        if use_default:
            return "萌哥，假设你是一个情场高手，性格风趣，滑稽有趣，并且能够准确的幽默回答她给你的问题，你的任务是对话过程中让她对你产生好感，每次回答只能回答30个字以内！"
        else:
            return simpledialog.askstring("自定义提示词", "请输入提示词描述(尽量给出完整和准确的提示词，可参考prompt.txt文件)：")

    def __ask(self, msg):
        response = self.client.chat.completions.create(
            model="deepseek-chat",
            messages=[
                {"role": "system", "content": self.prompt},
                {"role": "user", "content": msg},
            ],
            stream=False
        )
        return response.choices[0].message.content.strip()

    def run(self):
        wait = 2
        while True:
            msgs = self.wx.GetListenMessage()
            for chat in msgs:
                msg_list = msgs.get(chat)
                for item in msg_list:
                    if item.type == 'friend':
                        last_msg = self.last_messages.get(item.sender)
                        if item.content != last_msg:
                            reply = self.__ask(item.content)
                            print(f"\n接收 {item.sender} 的消息: {item.content}")
                            print(f"回复 {item.sender} 的消息: {reply}")
                            chat.SendMsg(reply)
                            self.last_messages[item.sender] = item.content
            time.sleep(wait)


if __name__ == "__main__":
    try:
        bot = WeChatBot()
        bot.run()
    except KeyboardInterrupt:
        pass
    except Exception as e:
        import traceback
        print("程序异常退出：", traceback.format_exc())
    finally:
        root = tk.Tk()
        root.withdraw()
        messagebox.showinfo("已退出", "程序已退出，感谢使用！")
